package com.blueocean_health.care.management.interceptor;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.blueocean_health.care.management.domain.base.SysResult;


@Aspect
public class WebRequestAroundAdvice {

	@Pointcut(value = "execution(* com.blueocean_health.care.management.controller.*.*(..))")
	public void pointcut() {
	}

	@Around("pointcut()")
	public Object handle(ProceedingJoinPoint joinPoint) throws Throwable {
		preHandle();

		Object retVal = joinPoint.proceed();

		postHandle(retVal);

		return retVal;
	}

	private void preHandle() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();

		StringBuffer sb = new StringBuffer();
		sb.append("{");

		Enumeration<String> headers = request.getHeaderNames();
		int i = 0;
		while (headers.hasMoreElements()) {
			String header = headers.nextElement();

			if (i > 0)
				sb.append(", ");
			sb.append(header + ": " + request.getHeader(header));
			i++;
		}
		sb.append("}");
		System.out.println(sb.toString());
	}

	private void postHandle(Object retVal) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		String header = request.getHeader("timestamp");
		try {
			((SysResult)retVal).setTimestamp(header);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		
	}

	private String getRequestInfo(HttpServletRequest request, boolean requestDetails) {
		StringBuffer sb = new StringBuffer();
		sb.append(request.getMethod()).append(" ");
		sb.append(request.getRequestURI());
		if (requestDetails) {
			Enumeration<String> e = request.getParameterNames();
			sb.append(" ").append("{");
			int i = 0;
			while (e.hasMoreElements()) {
				String name = e.nextElement();
				String val = request.getParameter(name);

				if (val != null && !val.isEmpty()) {
					if (i > 0)
						sb.append(", ");
					sb.append(name).append(": ").append(val);

					i++;
				}
			}
			sb.append("}");
		}

		return sb.toString();
	}
}
